package com.whg.push.meida;


import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.whg.push.LivePusher;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AudioChannel {
    private final ExecutorService executor;
    private final int minBufferSize;
    private LivePusher mLivePusher;
    private AudioRecord mAudioRecord;
    private int channels = 2;
    private int channelConfig;
    private boolean isLiving;
    private int inputSamlples;

    public void setChannels(int channels) {
        this.channels = channels;
    }

    public AudioChannel(LivePusher livePusher) {
        executor = Executors.newSingleThreadExecutor();
        mLivePusher = livePusher;
        if (channels == 2) {
            //双通道
            channelConfig = AudioFormat.CHANNEL_IN_STEREO;
        } else {
            channelConfig = AudioFormat.CHANNEL_IN_MONO;
        }
        mLivePusher.native_setAudioEncInfo(44100, channels);

        inputSamlples = mLivePusher.getInputSamples() * 2;
        minBufferSize = AudioRecord.getMinBufferSize(44100, channelConfig, AudioFormat.ENCODING_PCM_16BIT) * 2;
        mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, channelConfig, AudioFormat.ENCODING_PCM_16BIT, minBufferSize > inputSamlples ? inputSamlples : minBufferSize);

    }

    public void startLive() {
        isLiving = true;
        executor.submit(new AudioTask());
    }

    public void stopLive() {
        isLiving = false;
        executor.shutdownNow();
    }

    private class AudioTask implements Runnable {
        @Override
        public void run() {
            mAudioRecord.startRecording();
            //pcm
            byte[] bytes = new byte[inputSamlples];
            while (isLiving) {
                int len = mAudioRecord.read(bytes, 0, bytes.length);
                mLivePusher.native_pushAudio(bytes);
            }
        }
    }
}
